<?php
/**
 * Created by PhpStorm.
 * User: sunzexin
 * Date: 2018/1/4
 * Time: 14:58
 */

namespace App\Http\Logics\MiniProgram;


use App\PartyPhoto;
use function GuzzleHttp\Psr7\uri_for;

class PartyPhotoLogic extends BaseLogic
{
    /**
     * 更新活动图片
     * @param $data 图片信息
     * @return mixed 添加结果
     */
    public static function createPartyPhoto($data)
    {
        try {
            $image_text_party_photo = new PartyPhoto();
            $image_text_party_photo->party_id = $data['party_id'];
            $image_text_party_photo->url = $data['url'];
            $image_text_party_photo->body = $data['body'];
            $image_text_party_photo->width = $data['width'];
            $image_text_party_photo->height = $data['height'];
            if (!$image_text_party_photo->save()) {
                return self::response(self::OBJECT_SAVE_FAIL);
            }
            return self::response(self::SUCCESS);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 通过party_id获取活动图片
     * @param $data 筛选条件
     * @return mixed 返回结果
     */
    public static function getPartyPhotoList($data)
    {
        try {
            $party_photo = PartyPhoto::where('party_id', $data['party_id'])->get();
            if (empty($party_photo)) {
                return self::response(self::CONTENT_IS_EMPTY);
            }
            return self::response(self::SUCCESS, $party_photo);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 处理图片数组
     * @param $data 需要处理的数据
     * @return mixed 返回处理结果
     */
    public static function handlePartyPhotoArray($data)
    {
        try {
            $photos = PartyPhoto::where('party_id', $data['party_id'])->get();
            // 将之前与图文活动关联的图片删除掉
            foreach ($photos as $photo) {
                $photo->delete();
            }
            $photos_arr = json_decode($data['photo_list_str']);
            foreach ($photos_arr as $item) {
                $url = $item->url . "?imageInfo";
                // 处理图片
                $rs = dealHttp($url);
                $width = $rs->width;
                $height = $rs->height;
                $image_text_party_photo_data = [
                    'url' => $item->url,
                    'width' => $width,
                    'height' => $height,
                    'party_id' => $data['party_id'],
                    'body' => $item->body
                ];
                $response = self::createPartyPhoto($image_text_party_photo_data);
                if ($response->code) {
                    return self::response(self::OBJECT_SAVE_FAIL);
                }
            }
            return self::response(self::SUCCESS);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }
}